<?php


namespace app\api\business;

use app\api\model\UserModel;
use app\common\lib\Show;
use app\common\lib\Token;
use think\Exception;

class User
{
    private $user = null;

    public function __construct()
    {
        $this->user = new UserModel();
    }

    public function login($data)
    {
        // 密码使用 password_hash()加密、判断使用 password_verify($pass, $hash)
        $user = $this->user->getUserByUsername($data['username']);
        if ($user && password_verify($data['password'], $user->password)) {
            $token = Token::generate('admin');
            $data = [
                'id' => $user->id,
                'username' => $user->username,
                'token' => $token
            ];
            $res = cache(config('cache.stores.file.prefix') . $token, $data, config('cache.stores.file.expire'));
            return $res ? $data : [];
        }
        return [];
    }

    public function register($data){
        $user = $this->user->getUserByUsername($data['username']);
        if (!empty($user)){
            throw new Exception('用户已存在');
        }
        $res = $this->user->save($data);
        if (!$res){
            throw new Exception('数据库内部错误');
        }
        $id = (int)$this->user->id;
        $newUser = $this->user->find($id);
        if (!$newUser){
            return false;
        }
        $newUser = $newUser->toArray();
        unset($newUser['password']);
        return $newUser;
    }

}
